package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;

import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);


        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.clean(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 分页查询历史订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    //TODO 分页查询订单功能基础实现，还存在可以优化空间，1、尝试Redis数据库实现功能 2缺少业务场景判断
    public PageResult page(int page, int pageSize) {
        //开始分页
        PageHelper.startPage(page, pageSize);
        //1、查询出用户ID
        Long userId = BaseContext.getCurrentId();
        //2、查询出用户ID对应的所有订单
        Page<OrderVO> orderVOList = orderMapper.getUserId(userId);
        //3、根据订单ID查询订单详情表
        for (OrderVO orderVO : orderVOList) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        }
        //4、返回数据
        PageResult pageResult = new PageResult(orderVOList.getTotal(), orderVOList.getResult());
        return pageResult;

    }

    /**
     * 订单查询详情功能
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {

        OrderVO orderVO = orderMapper.getById(id);
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
        orderVO.setOrderDetailList(byOrderId);
        return orderVO;
    }


    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //1、业务场景判断
        OrderVO orderVO = orderMapper.getById(id);
        if (orderVO.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orderVO == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orderVO.setStatus(6);

        orderMapper.update(orderVO);

    }


    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());

        ShoppingCart shoppingCart = new ShoppingCart();

        for (OrderDetail orderDetail : orderDetailList) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 管理端订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        //1、开始分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //2、查询Order表中所有数据
        Page<OrderVO> orderVOList = orderMapper.selectAll(ordersPageQueryDTO);


        List<String> orderDetailList = new ArrayList<>();

        for (OrderVO orderVO : orderVOList) {

            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
            for (OrderDetail orderDetail : byOrderId) {
                String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + " ";
                orderDetailList.add(orderDish);

            }
            orderVO.setOrderDishes(StringUtils.strip(orderDetailList.toString(), "[]"));
        }


        return new PageResult(orderVOList.getTotal(), orderVOList.getResult());
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);


        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);

        return orderStatisticsVO;

    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */

    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
        orderVO.setOrderDetailList(byOrderId);

        return orderVO;

    }

    /**
     * 接单
     *
     * @param
     */
    @Override
    public void confirm(OrdersDTO ordersDTO) {
        Integer status = Orders.CONFIRMED;
        ordersDTO.setStatus(status);
        orderMapper.updateStatus(ordersDTO);
    }

    /**
     * 支付成功
     * @param
     * @param
     */
//    @Override
//    public void payMent(OrdersPaymentDTO ordersPaymentDTO) {
//        Orders build = OrderVO.builder().payStatus(Orders.PAID).number(ordersPaymentDTO.getOrderNumber()).status(Orders.TO_BE_CONFIRMED).payMethod(ordersPaymentDTO.getPayMethod()).build();
//        OrderVO orderVO = new OrderVO();
//        BeanUtils.copyProperties(build,orderVO);
//        orderMapper.updateByNumber(orderVO);
//    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);
        log.info("根据订单号查询：{}",ordersDB);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        log.info("查看VO：{}",orderVO);
        orderMapper.update(orderVO);
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orderVO.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
    }

    /**
     * 用户催单
     */
    @Override
    public void reminder(Long id) {
        OrderVO byId = orderMapper.getById(id);
        if (byId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + byId.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
